﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;

namespace FBGraph.Configuration
{
    /// <summary>A collection of <see cref="FBGraphApplicationElement" /> elements that makes up the list of FBGraph applications the application
    /// is equipped to service requests for.</summary>
    [ConfigurationCollection(typeof(FBGraphApplicationElement))]
    public class FBGraphApplicationElementCollection : ConfigurationElementCollection, IEnumerable<FBGraphApplicationElement>
    {
        /// <summary>Creates a new <see cref="FBGraphApplicationElement" />.</summary>
        /// <returns>A new <see cref="FBGraphApplicationElement" />.</returns>
        protected override ConfigurationElement CreateNewElement()
        {
            return new FBGraphApplicationElement();
        }

        /// <summary>Gets the element key for the specified <see cref="FBGraphApplicationElement" />.</summary>
        /// <param name="element">The <see cref="FBGraphApplicationElement" /> to return the key for.</param>
        /// <returns>An <see cref="Object" /> that acts as the key for the specified <see cref="FBGraphApplicationElement" />.</returns>
        protected override Object GetElementKey(ConfigurationElement element)
        {
            var app = (FBGraphApplicationElement)element;
            return app.Environment + app.ClientID;
        }

        /// <summary>Gets the <see cref="FBGraphApplicationElement" /> configured for the current environment.</summary>
        /// <returns>The <see cref="FBGraphApplicationElement" /> configured for the current environment.</returns>
        public FBGraphApplicationElement GetCurrent()
        {
            String _environment;
            _environment = ConfigurationManager.AppSettings["Environment"] ?? String.Empty;

            return (
                from app in this.OfType<FBGraphApplicationElement>()
                where (_environment == app.Environment || (String.IsNullOrEmpty(app.Environment)))
                orderby app.Environment == _environment
                select app).FirstOrDefault();
        }

        #region [ IEnumerable<FBGraphApplicationElement> Members ]

        IEnumerator<FBGraphApplicationElement> IEnumerable<FBGraphApplicationElement>.GetEnumerator()
        {
            return new ConfigurationElementEnumerator<FBGraphApplicationElement>(this);
        }

        #endregion

        #region [ IEnumerable Members ]

        IEnumerator IEnumerable.GetEnumerator()
        {
            return base.GetEnumerator();
        }

        #endregion
    }
}